import React, {useCallback, useEffect, useRef, useState} from "react";
import {useNavigation, useRoute} from "@react-navigation/native";
import {defaultNavigationConfigure} from "../../base/navconfig";
import StatusBarCtl from "../../utils/StatusBarCtl";
import {LoadingView} from "react-native-gzdsx-elements";
import {SafeAreaView, ScrollView, StyleSheet, Text, TouchableOpacity, View} from "react-native";
import ActionSheet from "react-native-actionsheet";
import ApiService from "../../utils/ApiService";
import {ListItem} from "react-native-elements";
import Icon from "react-native-vector-icons/AntDesign";
import FastImage from "react-native-fast-image";

const AddressView = ({onAddressChange = () => null}) => {
    const navigation = useNavigation();
    const [loading, setLoading] = useState(true);
    const [address, setAddress] = useState({});

    useEffect(() => {
        ApiService.get('/user/addresses/0').then(response => {
            setAddress(response.result);
            onAddressChange && onAddressChange(response.result);
        }).catch(reason => {
            console.log(reason.message);
        }).finally(() => {
            setLoading(false);
        })
    }, []);

    if (loading) {
        return <LoadingView style={{height: 100}}/>
    }


    if (address.id) {
        return (
            <ListItem
                containerStyle={styles.addressContainer}
                onPress={() => {
                    navigation.navigate('AddressAdmin', {choose: true});
                }}
            >
                <Icon
                    name={"enviromento"}
                    size={22}
                    color={"#666"}
                />
                <ListItem.Content>
                    <ListItem.Title style={styles.addressName}>{address.name}{'  '}{address.phone}</ListItem.Title>
                    <ListItem.Subtitle style={styles.addressDetail}>{address.formatted_address}</ListItem.Subtitle>
                </ListItem.Content>
                <ListItem.Chevron/>
            </ListItem>
        );
    } else {
        return (
            <ListItem
                containerStyle={styles.addressContainer}
                onPress={() => {
                    navigation.navigate('AddressAdmin', {choose: true});
                }}
            >
                <View style={{flexDirection: 'row', justifyContent: 'center', alignItems: 'center', flex: 1}}>
                    <Icon name={'plus'} size={20} color={"#333"}/>
                    <Text style={{lineHeight: 20, fontSize: 16, marginLeft: 5, color: '#333'}}>添加收货地址</Text>
                </View>
            </ListItem>
        )
    }
}

const FooterView = (props) => {
    return (
        <SafeAreaView style={{backgroundColor: '#fff'}}>
            <View style={{borderTopColor: '#e5e5e5', borderTopWidth: 0.5}}>
                <View style={{flexDirection: 'row', padding: 5}}>
                    <View style={{flex: 1, flexDirection: 'row', paddingHorizontal: 10}}>
                        <Text style={{
                            fontSize: 14,
                            color: '#333',
                            lineHeight: 49
                        }}>共{props.quantity}件商品，总计:</Text>
                        <Text style={{
                            color: '#f00',
                            fontSize: 15,
                            lineHeight: 49,
                        }}>￥{props.totalFee}</Text>
                    </View>
                    <TouchableOpacity
                        activeOpacity={1}
                        onPress={() => {
                            props.onSubmit && props.onSubmit();
                        }}
                        style={{paddingVertical: 5, paddingHorizontal: 10}}
                    >
                        <View style={{
                            paddingLeft: 20,
                            paddingRight: 20,
                            backgroundColor: '#FC461E',
                            flex: 1,
                            borderRadius: 20,
                            flexDirection: 'row',
                            justifyContent: 'center',
                            alignItems: 'center'
                        }}>
                            <Text style={{
                                color: '#fff',
                                fontSize: 14,
                                textAlign: 'center',
                            }}>提交订单</Text>
                        </View>
                    </TouchableOpacity>
                </View>
            </View>
        </SafeAreaView>
    );
}

const shippingTypes = {
    '1': '快递',
    '2': '到店自取'
};
const payTypes = {
    '1': '在线支付',
    '2': '货到付款'
};
const Checkout = () => {
    const route = useRoute();
    const navigation = useNavigation();

    const [loading, setLoading] = useState(true);
    const [sku, setSku] = useState({});
    const [product, setProduct] = useState({});
    const [quantity, setQuantity] = useState(1);
    const [shippingType, setShippingType] = useState(1);
    const [payType, setPayType] = useState(1);
    const [remark, setRemark] = useState('');
    const [totalFee, setTotalFee] = useState(0);
    const [address, setAddress] = useState({});

    const shippingAS = useRef(null);
    const payAS = useRef(null);

    useEffect(() => {
        navigation.setOptions({
            ...defaultNavigationConfigure(navigation),
            headerTitle: '确认订单',
        });
    }, [navigation]);

    useEffect(() => {
        fetchData();
        return navigation.addListener('focus', () => {
            StatusBarCtl.setToDarkStyle();
        });
    }, []);

    const fetchData = () => {
        ApiService.post('/checkout/calculate', route.params).then(response => {
            let res = response.result;
            setSku(res.sku);
            setProduct(res.product);
            setQuantity(res.quantity);
            setTotalFee(res.order_fee);
        }).catch(reason => {
            console.log(reason.message);
        }).finally(() => {
            setLoading(false);
        });
    }

    const submit = useCallback(
        () => {
            const data = {
                ...route.params,
                pay_type: payType,
                shipping_type: shippingType,
                remark,
                address
            }
            ApiService.post('/checkout/create-order', data).then(res => {
                let {order_id} = res.result;
                navigation.replace('OrderDetail',{order_id});
            }).catch(reason => {
                console.log(reason.message);
            });
        },
        [route.params, payType, shippingType, remark, address]
    );


    if (loading) {
        return <LoadingView/>;
    }

    return (
        <View style={{flex: 1, backgroundColor: '#f5f5f5'}}>
            <ScrollView style={{flex: 1}}>
                <AddressView onAddressChange={addr => {
                    setAddress(addr);
                }}/>
                <View style={{marginTop: 10, backgroundColor: '#fff'}}>
                    <ListItem>
                        <FastImage
                            source={{uri: product.image}}
                            style={styles.proImage}
                            resizeMode={FastImage.resizeMode.cover}
                        />
                        <ListItem.Content>
                            <Text style={styles.proTitle} numberOfLines={2}>{product.title}</Text>
                            {
                                sku.sku_id ?
                                    <View style={{flexDirection: 'row', marginTop: 5}}>
                                        <TouchableOpacity style={styles.skuTouch}>
                                            <Text style={{fontSize: 12, color: '#555'}}>{sku.title}</Text>
                                        </TouchableOpacity>
                                    </View>
                                    : null
                            }
                            <View style={{flexDirection: 'row', marginTop: 5}}>
                                <Text style={styles.proPrice}>￥{product.price}</Text>
                                <Text style={styles.proQuantity}>x{quantity}</Text>
                            </View>
                        </ListItem.Content>
                    </ListItem>
                    <ListItem onPress={() => shippingAS.current.show()}>
                        <ListItem.Content>
                            <ListItem.Title style={styles.label}>配送方式</ListItem.Title>
                        </ListItem.Content>
                        <ListItem.Subtitle style={styles.value}>{shippingTypes[shippingType]}</ListItem.Subtitle>
                        <ListItem.Chevron/>
                    </ListItem>
                    <ListItem onPress={() => payAS.current.show()}>
                        <ListItem.Content>
                            <ListItem.Title style={styles.label}>付款方式</ListItem.Title>
                        </ListItem.Content>
                        <ListItem.Subtitle style={styles.value}>{payTypes[payType]}</ListItem.Subtitle>
                        <ListItem.Chevron/>
                    </ListItem>
                    <ListItem>
                        <ListItem.Title style={styles.label}>给卖家留言</ListItem.Title>
                        <ListItem.Input
                            inputStyle={styles.input}
                            placeholder={"选填,对本次交易的说明"}
                            onChangeText={(text) => setRemark(text)}
                        />
                    </ListItem>
                </View>
            </ScrollView>
            <FooterView quantity={quantity} totalFee={totalFee} onSubmit={submit}/>
            <ActionSheet
                ref={shippingAS}
                options={Object.values(shippingTypes).concat('取消')}
                cancelButtonIndex={2}
                onPress={(index) => {
                    if (index < 2) {
                        const keys = Object.keys(shippingTypes);
                        setShippingType(keys[index]);
                    }
                }}
            />
            <ActionSheet
                ref={payAS}
                options={Object.values(payTypes).concat('取消')}
                cancelButtonIndex={2}
                onPress={(index) => {
                    if (index < 2) {
                        const keys = Object.keys(payTypes);
                        setPayType(keys[index]);
                    }
                }}
            />
        </View>
    );
}

export default Checkout;

const styles = StyleSheet.create({
    addressName: {
        fontSize: 16,
        color: '#666'
    },
    addressDetail: {
        fontSize: 14,
        color: '#666',
        marginTop: 5
    },
    addressContainer: {
        paddingVertical: 20
    },
    label: {
        fontSize: 14,
        color: '#333'
    },
    value: {
        fontSize: 14,
        color: '#838383'
    },
    input: {
        fontSize: 14,
        textAlign: 'left'
    },
    proImage: {
        width: 80,
        height: 80,
        borderRadius: 3,
        marginRight: 10
    },
    proTitle: {
        fontSize: 14,
        color: '#333',
    },
    skuTouch: {
        backgroundColor: '#f2f2f2',
        paddingHorizontal: 5,
        paddingVertical: 3,
        borderRadius: 5
    },
    proPrice: {
        color: '#f00',
        fontSize: 14,
        fontWeight: '500',
        flex: 1
    },
    proQuantity: {
        fontSize: 14,
        color: '#333'
    }
})
